package com.zjp.strategy;

import com.zjp.enums.StrategyEnums;
import com.zjp.strategy.impl.AddStrategyImpl;
import com.zjp.strategy.impl.SubtractStrategyImpl;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Component
public class StrategyContext implements ApplicationContextAware {

    Map<StrategyEnums, Strategy> strategyMap;

    public StrategyContext() {
        strategyMap = new HashMap<>();
    }

    public int start(StrategyEnums enums, int num1, int num2) {
        Strategy strategy = strategyMap.get(enums);
        if (Objects.isNull(strategy)) {
            throw new RuntimeException("未找到对应的策略模式");
        }
        return strategy.intOperation(num1, num2);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        strategyMap.put(StrategyEnums.Add, applicationContext.getBean(AddStrategyImpl.class));
        strategyMap.put(StrategyEnums.Subtract, applicationContext.getBean(SubtractStrategyImpl.class));
    }
}
